﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GTServices.Entities;
using GTServices.WPF.Client.ViewModels;
using GTServices.Model.Extensions;
using ICSharpCode.AvalonEdit;

using ICSharpCode.AvalonEdit.Search;
using ICSharpCode.AvalonEdit.Highlighting;


namespace GTServices.WPF.Client.Controls
{
    /// <summary>
    /// Interaction logic for AvalonEditControl.xaml
    /// </summary>
    public partial class AvalonEditControl : TextEditor
    {
        public static void OnFileInfoChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)
        {
            var control = (AvalonEditControl)sender;

            var oldFile = (FileInfo)eventArgs.OldValue;
            var newFile = (FileInfo)eventArgs.NewValue;


            if (oldFile == null || (oldFile != newFile))
            {
                try
                {
                    if (System.IO.File.Exists(newFile.FullName))
                    {
                        System.IO.StreamReader sr = new System.IO.StreamReader(newFile.FullName);
                        String s = sr.ReadToEnd();

                        //TODO: Add code to editor. 
                        control.Text = s;
                        control.SyntaxHighlighting = HighlightingManager.Instance.GetDefinitionByExtension(control.FileInfo.FileExtension.Extension);
                    }
                    else
                    {
                        //TODO: 

                    }
                }
                catch
                {

                }
            }
            control.FileInfo = newFile;
        }

        public static readonly DependencyProperty FileInfoProperty = DependencyProperty.RegisterAttached("FileInfo", typeof(FileInfo), typeof(AvalonEditControl), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnFileInfoChanged)));

        public FileInfo FileInfo
        {
            get
            {
                return (FileInfo)GetValue(FileInfoProperty);
            }

            set
            {
                SetValue(FileInfoProperty, value);
            }
        }

        public AvalonEditControl()
        {
            InitializeComponent();
            this.ShowLineNumbers = true;
            this.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
            this.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
        }
   
    }
}
